package cn.com.czpb.client.services;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;

import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.model.diantai.RadioTypeBean;
import cn.com.czpb.client.model.diantai.RadioTypeEntity;
import cn.com.czpb.client.model.livenew.LiveTypeBean;
import cn.com.czpb.client.model.livenew.LiveTypeEntity;
import cn.com.czpb.client.model.news.AreaChannelBean;
import cn.com.czpb.client.model.news.AreaLocationChannelEntity;
import cn.com.czpb.client.model.news.AreaOtherChannelBean;
import cn.com.czpb.client.model.news.NewsChannelBean;
import cn.com.czpb.client.model.news.NewsChannelBean1;
import cn.com.czpb.client.model.news.NewsChannelEntity;
import cn.com.czpb.client.model.welcome.ImageEntity;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.SPUtil;

import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/6/30.
 */

public class InitService extends IntentService {
    private SPUtil spu;
    public static final String InitAction = "initServer";
    private List<NewsChannelBean> listNew;
    private List<AreaChannelBean> listCity;
    private List<AreaOtherChannelBean> listCountry;
    public InitService() {
        super("InitService");
    }

    public Boolean isUpdata = false;

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.i("oncreate");
        listNew = new ArrayList<>();
        listCity = new ArrayList<>();
        listCountry = new ArrayList<>();
        spu = SPUtil.getInstance();
        if (spu.getShowImage() == null) {
            spu.setShowImage("0");
        }
        if (spu.getWifi() == null) {
            spu.setWifi("1");
        }
    }
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent != null) {
            if (InitAction.equals(intent.getAction())) {
                LogUtils.i("initserver-->1");
                getWelcomePic();
                getChannelJson();
                getLiveType();
                getRadioType();
            }
        }
    }
    /**
     * 开屏图获取
     */
    private void getWelcomePic() {
        Factory.provideHttpService()
                .welcomeAd()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ImageEntity>() {
                    @Override
                    public void onCompleted() {
                        LogUtils.i("onCompleted-->");
                    }
                    @Override
                    public void onError(Throwable e) {
                        LogUtils.i("imgerror-->");
                        e.printStackTrace();
                    }
                    @Override
                    public void onNext(ImageEntity entity) {
                        StringBuilder sb = new StringBuilder();
//                        for (String imgurl : entity.data.getImgurl()) {
//                            sb.append(imgurl);
//                            sb.append(",");
//                        }
//                        String imgStr = sb.toString();
                        LogUtils.i("imgurl-->"+entity.data.getImgurl());
                        SPUtil.getInstance().setWelcome(entity.data.getImgurl());
                    }
                });
    }
    //获取,栏目title;
    private void getChannelJson() {
        LogUtils.i("init", "getChannelJson");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("flag", "1");
        Factory.provideHttpService()
                .newsChannellistNew(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsChannelEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsChannelEntity entity) {
                        LogUtils.e("code--" + entity.code);
                        LogUtils.i("initserver-->2");
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsChannelEntity>() {
                    @Override
                    public void call(NewsChannelEntity entity) {
                        LitePal.deleteAll(NewsChannelBean1.class);
                        LitePal.saveAll(entity.data.getWemedia());

                        String oldChannels = spu.getChannels();
                        LogUtils.i("channel1-->" + oldChannels);
                        listNew.addAll(entity.data.getCommon());
                        StringBuilder sb = new StringBuilder();
                        for (int j = 0; j < listNew.size(); j++) {
                            String titleNew = listNew.get(j).getCnname();
                            String type = listNew.get(j).getType();
                            sb.append(titleNew);
                            sb.append(type);
                        }
                        spu.setChannels(sb.toString());
                        LogUtils.i("channel2-->" + spu.getChannels());

                        List<NewsChannelBean> list = DataSupport.findAll(NewsChannelBean.class);
                        if (list!=null&&sb.toString() != null && sb.toString().equals(oldChannels)) {

                                LogUtils.i("channel3-->");
                        } else {
                            LogUtils.i("channel4-->");
                            for (NewsChannelBean bean : entity.data.getCommon()
                                    ) {
                                bean.setIschoice("1");
                            }
                            LogUtils.i("listsize-->2" + entity.data.getCommon());
                            DataSupport.deleteAll(NewsChannelBean.class);
                            DataSupport.saveAll(entity.data.getCommon());

                        }

                    }


//                        List<NewsChannelBean> list = DataSupport.findAll(NewsChannelBean.class);
//                        LogUtils.i("listsize-->" + list.size());
//                        listNew.addAll(entity.data.getCommon());
//                        int count = 0;
//                        int size = entity.data.getCommon().size();
//                        if (list != null && entity.data != null && list.size() == size) {
//                            for (int i = 0; i < list.size(); i++) {
//                                String title = list.get(i).getCnname();
//                                for (int j = 0; j < listNew.size(); j++) {
//                                    String titleNew = listNew.get(j).getCnname();
//                                    if (titleNew.equals(title)) {
//                                        count++;
//                                        break;
//                                    }
//                                }
//                            }
//                            if (count != list.size()) {
//                                for (NewsChannelBean bean : entity.data.getCommon()
//                                        ) {
//                                    bean.setIschoice("1");
//
//                                }
//                                DataSupport.deleteAll(NewsChannelBean.class);
//
//                                DataSupport.saveAll(entity.data.getCommon());
//                            }
//                        } else if (entity.data != null) {
//                            for (NewsChannelBean bean : entity.data.getCommon()
//                                    ) {
//                                bean.setIschoice("1");
//                            }
//                            LogUtils.i("listsize-->2" + entity.data.getCommon());
//                            DataSupport.deleteAll(NewsChannelBean.class);
//                            DataSupport.saveAll(entity.data.getCommon());
//                        }
//                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable-->" + throwable.toString());
                    }
                });
        {
            Map<String, String> map2 = new HashMap<>();
            map2.put("siteid", InterfaceJsonfile.SITEID);
            map2.put("id", "1");
            Factory.provideHttpService()
                    .getArealistLocation(ParamUtils.getRequestParam(map2))
                    .subscribeOn(Schedulers.io())
                    .filter(new Func1<AreaLocationChannelEntity, Boolean>() {
                        @Override
                        public Boolean call(AreaLocationChannelEntity entity) {
                            LogUtils.e("code--" + entity.code);
                            return "200".equals(entity.code);
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<AreaLocationChannelEntity>() {
                        @Override
                        public void call(AreaLocationChannelEntity entity) {
                            HashMap map = new HashMap();
                            for (AreaChannelBean bean:entity.data.getCommon()) {
                                map.put(bean.getName(),bean);
                            }
                            for (AreaChannelBean bean2:entity.data.getOther()) {
                                map.put(bean2.getName(),bean2);
                            }
                            spu.putHashMapData("cityMap",map);
                            spu.setCurrentCounty(null);
                            spu.setCurrentCountryPosition(0);
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            LogUtils.i("throwable-->" + throwable.toString());
                        }
                    });
        }
    }
    private void  getLiveType(){
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .getliveType(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<LiveTypeEntity, Boolean>() {
                    @Override
                    public Boolean call(LiveTypeEntity entity) {
                        LogUtils.e("code--" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LiveTypeEntity>() {
                    @Override
                    public void call(LiveTypeEntity entity) {

                        int size=entity.data.size();
                        LogUtils.e("code--" + "直播频道"+size);
                        for (int i = 0; i <size ; i++) {
                            LiveTypeBean bean=entity.data.get(i);
                            bean.save();
                        }
                        List<LiveTypeBean>  list = LitePal.findAll(LiveTypeBean.class);
                        LogUtils.e("code--" + "直播频道"+list.size());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable-->" + throwable.toString());
                    }
                });
    }
    private void  getRadioType(){
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .getdiantaiType(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<RadioTypeEntity, Boolean>() {
                    @Override
                    public Boolean call(RadioTypeEntity entity) {
                        LogUtils.e("code--" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<RadioTypeEntity>() {
                    @Override
                    public void call(RadioTypeEntity entity) {
                        int size=entity.data.size();
                        LogUtils.e("code--" + "电台直播"+size);
                        for (int i = 0; i <size ; i++) {
                            RadioTypeBean bean=new RadioTypeBean();
                            bean.setTid(entity.data.get(i).getTid());
                            bean.setName(entity.data.get(i).getName());
                            bean.setSortOrder(entity.data.get(i).getSortOrder());
                            bean.save();

                        }
                        List<RadioTypeBean>  list = LitePal.findAll(RadioTypeBean.class);
                        LogUtils.e("code--" + "电台直播"+list.size());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable-->" + throwable.toString());
                    }
                });
    }

    private void getLiveType2() {
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        Factory.provideHttpService()
                .getliveType(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<LiveTypeEntity, Boolean>() {
                    @Override
                    public Boolean call(LiveTypeEntity entity) {
                        LogUtils.e("code--" + entity.code);
                        return "200".equals(entity.code);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<LiveTypeEntity>() {
                    @Override
                    public void call(LiveTypeEntity entity) {
                        int size = entity.data.size();
                        for (int i = 0; i < size; i++) {
                            LiveTypeBean bean = entity.data.get(i);
                            bean.save();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("throwable-->" + throwable.toString());
                    }
                });
    }




}
